package com.ruoyi.app.adapter;

import android.graphics.drawable.Drawable
import androidx.appcompat.widget.AppCompatImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.hjq.shape.view.ShapeTextView
import com.ruoyi.app.R

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject-Kotlin
 *    time   : 2021/02/28
 *    desc   : 导航栏适配器
 */
class NavigationAdapter constructor(val list: MutableList<MenuItem>) :
    BaseQuickAdapter<NavigationAdapter.MenuItem, BaseViewHolder>(
        R.layout.main_navigation_item, list
    ) {
    /** 当前选中条目位置 */
    private var selectedPosition: Int = 0

    /** 导航栏点击监听 */
    private var listener: OnNavigationListener? = null

    fun getSelectedPosition(): Int {
        return selectedPosition
    }

    fun setSelectedPosition(position: Int) {
        selectedPosition = position
        notifyDataSetChanged()
    }

    /**
     * 设置导航栏监听
     */
    fun setOnNavigationListener(listener: OnNavigationListener?) {
        this.listener = listener
    }

    class MenuItem constructor(private val text: String?, private val drawable: Drawable?) {

        fun getText(): String? {
            return text
        }

        fun getDrawable(): Drawable? {
            return drawable
        }
    }

    interface OnNavigationListener {
        fun onNavigationItemSelected(position: Int): Boolean
    }

    override fun convert(holder: BaseViewHolder, item: MenuItem) {

        val iconView = holder.getView<AppCompatImageView>(R.id.iv_home_navigation_icon)
        val titleView = holder.getView<ShapeTextView>(R.id.tv_home_navigation_title)
        val position = list.indexOf(item)
        iconView.isSelected = (selectedPosition == position)
        titleView.isSelected = (selectedPosition == position)

        iconView.setImageDrawable(item.getDrawable())
        titleView.text = item.getText()
        holder.itemView.setOnClickListener {
            if (selectedPosition == position) {
                return@setOnClickListener
            }
            if (listener == null) {
                selectedPosition = position
                notifyDataSetChanged()
                return@setOnClickListener
            }
            if (listener!!.onNavigationItemSelected(position)) {
                selectedPosition = position
                notifyDataSetChanged()
            }
        }

    }

}